package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.model.mongo.Voice;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;
import java.util.Random;

@DubboService
public class VoiceApiImpl implements VoiceApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    //删除以拾取的语音
    @Override
    public List<Voice> delVoice() {
        Query query = Query.query(Criteria.where("collect").is(1));
        //查询被拾取的
        List<Voice> list = mongoTemplate.find(query, Voice.class);
        //删除被拾取的
        mongoTemplate.remove(query, Voice.class);
        return list;
    }

    //随机查询语音
    @Override
    public Voice find(Long userId) {
        Query query = Query.query(Criteria.where("collect")
                .is(0).and("userId").ne(userId));
        List<Voice> voices = mongoTemplate.find(query, Voice.class);
        if (CollUtil.isNotEmpty(voices)) {
            int i = new Random().nextInt(voices.size());
            Voice voice = voices.get(i);
            //修改状态
            ObjectId id = voice.getId();
            Query query1 = Query.query(Criteria.where("id").is(id));
            Update update = new Update();
            update.set("collect",1);
            update.set("collectUserId", userId);
            mongoTemplate.updateFirst(query1, update, Voice.class);
            return voice;
        }
        return null;
    }

    //保存桃花传音
    @Override
    public void save(Voice voice) {
        mongoTemplate.save(voice);
    }
}
